<!--
 * @FilePath: /my-map-demo/src/components/Sidebar.vue
 * @Author: 张文鑫
 * @Date: 2024-11-30 22:15:03
 * @Description: 
-->
<template>
  <div class="sidebar">
    <el-menu
      :default-active="activeMenu"
      active-text-color="#ffd04b"
      background-color="#545c64"
      class="el-menu-vertical-demo"
      text-color="#fff"
      mode="vertical"
      :unique-opened="true"
      :router="true"
    >
      <!-- 动态生成一级菜单 -->
      <template v-for="menu in filteredRoutes" :key="menu.key">
        <el-sub-menu v-if="menu.children && menu.children.length && menu.meta?.showInSidebar" :index="menu.path">
          <template #title>
            <el-icon>
              <component :is="menu.meta?.icon" />
            </el-icon>
            <span>{{ menu.name }}</span>
          </template>
          <el-menu-item v-for="subMenu in menu.children" :key="subMenu.key" :index="subMenu.path">
            <span>{{ subMenu.name }}</span></el-menu-item
          >
        </el-sub-menu>

        <el-menu-item v-else @click="toPage(menu.path)" :index="menu.path">
          <el-icon>
            <component :is="menu.meta?.icon" />
          </el-icon>
          <span>{{ menu.name }}</span>
        </el-menu-item>
      </template>
    </el-menu>
  </div>
</template>

<script setup>
import { ref, watch, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { routes } from "@/router/index.js";
// 过滤掉不需要显示的路由
const filteredRoutes = routes.filter((route) => route.meta?.showInSidebar !== false);
// 当前高亮的菜单项
const route = useRoute();
const activeMenu = ref(route.path);
const router = useRouter();

const toPage = (url) => {
  router.push(url);
};

// 监听路由变化，更新当前菜单的高亮
watch(
  () => route.path,
  (newPath) => {
    activeMenu.value = newPath;
  }
);
</script>

<style scoped>
.sidebar {
  width: 200px;
  transition: width 0.3s ease;
}

/* 折叠样式控制 */
.sidebar-menu.is-collapsed .el-menu-item {
  justify-content: center;
}

.sidebar-menu.is-collapsed .el-submenu {
  margin-left: 0;
}

.sidebar-menu.is-collapsed .el-menu-item span {
  display: none;
}

.sidebar-menu.is-collapsed .el-icon {
  font-size: 18px;
}
</style>
